package com.example.shixunqq;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.Constraints;

import androidx.work.WorkManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.bumptech.glide.Glide;
import com.example.shixunqq.chart.SimpleLineChart;
import com.example.shixunqq.databinding.ActivityWeatherBinding;
import com.example.shixunqq.gson.AQI;
import com.example.shixunqq.gson.Forecast;
import com.example.shixunqq.gson.NowWeather;
import com.example.shixunqq.gson.Suggest;
import com.example.shixunqq.service.LocationService;
import com.example.shixunqq.service.PoiSearchService;
import com.example.shixunqq.service.WeatherUpdateWorker;
import com.example.shixunqq.util.HttpUtil;
import com.example.shixunqq.util.Utility;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.annotations.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    private SimpleLineChart hourlyChart;
    private SimpleLineChart dailyChart;
    private ImageView locationButton;
    private LocationService locationService;

    public static final String FORECAST_URL = "https://na5ctu3bgr.re.qweatherapi.com/v7/weather/7d";
    public static final String HOURLY_URL = "https://na5ctu3bgr.re.qweatherapi.com/v7/weather/24h";
    public static final String AQI_URL = "https://na5ctu3bgr.re.qweatherapi.com/v7/air/now";
    public static final String SUGGEST_URL = "https://na5ctu3bgr.re.qweatherapi.com/v7/indices/1d";
    public static final String NOWWEATHER_URL = "https://na5ctu3bgr.re.qweatherapi.com/v7/weather/now";
    public static final String KEY = "dd04f72e142b498c8366cca2c7661c78";
    private String current_province;
    private String current_city;
    private String current_county;
    private String type = "1,3,8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        hourlyChart = findViewById(R.id.hourly_chart);
        dailyChart = findViewById(R.id.daily_chart);
        
        // 初始化定位按钮
        locationButton = findViewById(R.id.location_button);
        locationButton.setOnClickListener(v -> startLocationUpdate());
        
        Intent intent = getIntent();
        String weatherId = intent.getStringExtra("weather_id");
        current_province = intent.getStringExtra("current_province");
        current_city = intent.getStringExtra("current_city");
        current_county = intent.getStringExtra("current_county");
        TextView titleCity = findViewById(R.id.title_city);
        titleCity.setText(String.format("%s %s %s", current_province, current_city, current_county));

        weatherId = weatherId.substring(2);
        requestWeather(weatherId);
        loadBingPic();
        
        // 初始化定位服务
        initLocationService();
        
        // 设置定期更新天气的WorkManager
        initWeatherUpdateWork();
    }

    private void startLocationUpdate() {
        if (locationService == null) {
            locationService = new LocationService(this, new LocationService.LocationCallback() {
                @Override
                public void onLocationSuccess(AMapLocation location) {
                    String adCode = location.getAdCode();
                    // 更新当前位置信息
                    current_province = location.getProvince();
                    current_city = location.getCity();
                    current_county = location.getDistrict();
                    
                    // 更新标题
                    runOnUiThread(() -> {
                        TextView titleCity = findViewById(R.id.title_city);
                        titleCity.setText(String.format("%s %s %s", current_province, current_city, current_county));
                        
                        // 请求新位置的天气
                        requestWeather(adCode);
                        Toast.makeText(WeatherActivity.this, "定位成功", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onLocationFailed(String error) {
                    runOnUiThread(() -> 
                        Toast.makeText(WeatherActivity.this, "定位失败: " + error, Toast.LENGTH_SHORT).show()
                    );
                }
            });
        }
        locationService.startLocation();
    }

    private void loadBingPic() {
        String url = "https://api.xygeng.cn/openapi/bing/";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(WeatherActivity.this, "获取Bing每日图片失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                com.coolweather.android.gson.BingPic bingPic = new Gson().fromJson(result, com.coolweather.android.gson.BingPic.class);
                Log.d("TAG123", result);
                runOnUiThread(() -> {
                    if (bingPic != null && bingPic.getCode() == 200) {
                        //加载图片
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    } else {
                        Toast.makeText(WeatherActivity.this, "获取Bing每日图片失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void requestWeather(String location) {
        // 获取24小时天气数据
        String hourlyUrl = HOURLY_URL + "?location=" + location + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(hourlyUrl, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, "获取24小时天气数据失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                try {
                    // 解析24小时天气数据
                    com.example.shixunqq.gson.HourlyWeather hourlyWeather = new Gson().fromJson(result, com.example.shixunqq.gson.HourlyWeather.class);
                    if (hourlyWeather != null && "200".equals(hourlyWeather.getCode())) {
                        List<Float> temperatures = new ArrayList<>();
                        List<String> times = new ArrayList<>();
                        for (com.example.shixunqq.gson.HourlyWeather.HourlyItem item : hourlyWeather.getHourly()) {
                            temperatures.add(Float.parseFloat(item.getTemp()));
                            times.add(item.getFxTime().substring(11, 16)); // 只显示时:分
                        }
                        runOnUiThread(() -> {
                            hourlyChart.setData(temperatures, times);
                            hourlyChart.setLineColor(Color.BLUE);
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // 获取7天天气数据
        String url1 = FORECAST_URL + "?location=" + location + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url1, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                Forecast forecast = Utility.handleForecastResponse(result);
                showForecastInfo(forecast);
                
                // 处理图表数据
                if (forecast != null && "200".equals(forecast.getCode())) {
                    List<Float> maxTemps = new ArrayList<>();
                    List<Float> minTemps = new ArrayList<>();
                    List<String> dates = new ArrayList<>();
                    
                    for (Forecast.DailyDTO daily : forecast.getDaily()) {
                        maxTemps.add(Float.parseFloat(daily.getTempMax()));
                        minTemps.add(Float.parseFloat(daily.getTempMin()));
                        dates.add(daily.getFxDate().substring(5)); // 只显示月-日
                    }
                    
                    runOnUiThread(() -> {
                        dailyChart.setData(maxTemps, dates);
                        dailyChart.setLineColor(Color.RED);
                    });
                }
            }
        });

        String url0 = NOWWEATHER_URL + "?" + "location=" + location + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url0, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(WeatherActivity.this, "获取当前天气信息失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                NowWeather nowWeather = Utility.handleNowWeatherResponse(result);
                Log.d("TAG23", result);
                showNowWeatherInfo(nowWeather);
            }
        });

        String url2 = AQI_URL + "?" + "location=" + location + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url2, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                AQI aqi = Utility.handleAQIResponse(result);
                Log.d("TAG23456", result);
                showAQIInfo(aqi);
            }
        });

        String url3 = SUGGEST_URL + "?" + "location=" + location + "&key=" + KEY + "&type=" + type;
        HttpUtil.sendOkHttpRequest(url3, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                Suggest suggest = Utility.handleSuggestResponse(result);
                Log.d("TAG2345666", result);
                showSuggestInfo(suggest);
                Log.d("TAG2345666", suggest.toString());
            }
        });
    }

    private void showNowWeatherInfo(NowWeather nowWeather) {
        runOnUiThread(() -> {
            if (nowWeather != null && nowWeather.getCode().equals("200")) {
                String temp = nowWeather.getNow().getTemp();
                String weatherText = nowWeather.getNow().getText();
                binding.includeNow.weatherInfoText.setText(weatherText);
                binding.includeNow.degreeText.setText(String.format("%s ℃", temp));
                
                // 设置天气图标
                int weatherIconRes = getWeatherIconResource(weatherText);
                binding.includeNow.weatherIcon.setImageResource(weatherIconRes);
            } else {
                Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int getWeatherIconResource(String weatherText) {
        // 根据天气文本返回对应的图标资源ID（支持简繁体）
        if (weatherText.contains("晴") || weatherText.contains("晴")) {
            return R.drawable.ic_weather_sunny;
        } else if (weatherText.contains("多云") || weatherText.contains("多雲")) {
            return R.drawable.ic_weather_cloudy;
        } else if (weatherText.contains("阴") || weatherText.contains("陰")) {
            return R.drawable.ic_weather_cloudy;
        } else if (weatherText.contains("雷") || weatherText.contains("雷")) {
            return R.drawable.ic_weather_thunder;
        } else if (weatherText.contains("小雨") || weatherText.contains("小雨")) {
            return R.drawable.ic_weather_light_rain;
        } else if (weatherText.contains("中雨") || weatherText.contains("中雨")) {
            return R.drawable.ic_weather_moderate_rain;
        } else if (weatherText.contains("大雨") || weatherText.contains("大雨")) {
            return R.drawable.ic_weather_heavy_rain;
        } else if (weatherText.contains("雾") || weatherText.contains("霧")) {
            return R.drawable.ic_weather_foggy;
        } else {
            return R.drawable.ic_weather_unknown;
        }
    }

    private void showSuggestInfo(Suggest suggest) {
        runOnUiThread(() -> {
            if (suggest != null && suggest.getCode().equals("200")) {
                binding.includeSuggestion.comfortText.setText(String.format("舒适度指数：\n%s\n%s",
                        suggest.getDaily().get(2).getCategory(),
                        suggest.getDaily().get(2).getText()));
                binding.includeSuggestion.sportText.setText(String.format("运动指数：\n%s\n%s",
                        suggest.getDaily().get(0).getCategory(),
                        suggest.getDaily().get(0).getText()));
                binding.includeSuggestion.wearText.setText(String.format("穿衣指数：\n%s\n%s",
                        suggest.getDaily().get(1).getCategory(),
                        suggest.getDaily().get(1).getText()));
            } else {
                Toast.makeText(this, "获取天气指数出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showAQIInfo(AQI aqi) {
        runOnUiThread(() -> {
            if (aqi != null && aqi.getCode().equals("200")) {
                binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
                binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
            } else {
                Toast.makeText(this, "获取实时空气质量出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showForecastInfo(Forecast forecast){
        runOnUiThread(()->{
            if(forecast!=null&&forecast.getCode().equals("200")){
                binding.includeForecast.forecastLayout.removeAllViews();
                for (Forecast.DailyDTO dailyDTO : forecast.getDaily()){
                    View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, binding.includeForecast.forecastLayout,  false);
                    TextView dateText = view.findViewById(R.id.date_text);
                    TextView infoText = view.findViewById(R.id.info_text);
                    TextView maxText = view.findViewById(R.id.max_text);
                    TextView minText = view.findViewById(R.id.min_text);
                    ImageView weatherIcon = view.findViewById(R.id.weather_icon);

                    dateText.setText(dailyDTO.getFxDate());
                    String weatherText = dailyDTO.getTextDay();
                    infoText.setText(weatherText);
                    maxText.setText(dailyDTO.getTempMax());
                    minText.setText(dailyDTO.getTempMin());
                    
                    // 设置天气图标
                    weatherIcon.setImageResource(getWeatherIconResource(weatherText));
                    
                    binding.includeForecast.forecastLayout.addView(view);
                }
            }else{
                Toast.makeText(this, "获取未来7天天气预报出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initLocationService() {
        LocationService locationService = new LocationService(this, new LocationService.LocationCallback() {
            @Override
            public void onLocationSuccess(AMapLocation location) {
                // 保存当前位置
                SharedPreferences.Editor editor = getSharedPreferences("weather_data", MODE_PRIVATE).edit();
                editor.putString("current_location", location.getAdCode());
                editor.apply();
                
                // 使用POI搜索附近地点
                searchNearbyPoi(location);
            }

            @Override
            public void onLocationFailed(String error) {
                Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        });
        locationService.startLocation();
    }
    
    private void searchNearbyPoi(AMapLocation location) {
        PoiSearchService poiSearchService = new PoiSearchService(this, new PoiSearchService.PoiSearchCallback() {
            @Override
            public void onPoiSearchSuccess(List<PoiItem> poiItems) {
                // 处理POI搜索结果
                StringBuilder poiInfo = new StringBuilder("附近地点：\n");
                for (PoiItem item : poiItems) {
                    poiInfo.append(item.getTitle()).append(" - ").append(item.getDistance()).append("米\n");
                }
                // 可以在UI上显示POI信息
            }

            @Override
            public void onPoiSearchFailed(String error) {
                Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
            }
        });
        
        // 搜索1000米范围内的地点
        poiSearchService.searchNearbyPoi(
            new LatLonPoint(location.getLatitude(), location.getLongitude()),
            "",  // 空字符串表示搜索所有类型
            1000
        );
    }
    
    private void initWeatherUpdateWork() {
        // Implementation of initWeatherUpdateWork method
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            locationService.stopLocation();
        }
    }
}

